import doT from '../../../../vendor/template/doT.js';
import {
	auditStateToHtml
} from "../../../common/json-mapping/state-content-mapping.js";
import watermark from '../../../common/watermark.js';
import PigProcurementPlanApi from '../../../common/api/food/pigprocurementplan.api.js';

(function(window, document, $) {
	const salesplanmainTemplate = doT.template($('#pigprocurementplan-template').text());
	let _vm, _res, resTotal = [],
		operatarr = [],
		index
	let _dateFilter = {
		startDate: '',
		endDate: ''
	}
	let _page = {
		pageSize: 10,
		pageIndex: 0,
		// totalPages: -1,
	}
	$(function() {
		_vm = new Vue({
			el: "#pigprocurementplan",
			data() {
				return {
					salesplanList: [],
					page: {
						..._page
					}
				}
			}
		});
		$('body').attr('data-weui-theme', 'light'); //强制光明模式

		_initCommand();
		_initDatePicker(); // 初始化日期选择器
		_initSlide(); // 下拉加载
		_ctlReturn(); // 控制返回按钮，返回的页面
		pullLoad(); // 上拉加载
		_returnMain(); // 返回首页
		_watermarkBgImg(); // 添加水印信息
		_initDataTable(); // 初始加载数据
	});

	//TODO : 命名初始化
	const _initCommand = () => {
		// 新增按钮
		$('#addsaleorders').on('click', function(e) {
			window.sessionStorage.removeItem("pigprocurementplan_edit_id");
			window.sessionStorage.removeItem("pigprocurementplan_data");
			location.href = `../certregs/addpigprocurementplan.html?v=${Utils.GetTime()}`;
		});

		// 显示功能可视区
		$(document).on('click', '.ellipsis', function(e) {
			$(document).off("click", ".looksale")
			e.stopPropagation()
			$(".saleElp").siblings('.detail').css('display', 'none')
			$(this).parents(".salesplanstate").siblings('.detail').css('display', 'block')
			index = $(this).parents('.looksale').index()
			let billindex = resTotal[index].billStatus
			let $opration = $(this).parents('.saleElp').siblings('.detail')

			// 重置所有按钮显示
			$opration.find('li').css('display', 'block')

			// 已保存 (1) - 可以编辑、提交、删除
			if (billindex === 1) {
				$opration.find('.audit').css('display', 'none')
				$opration.find('.antiaudit').css('display', 'none')
			}
			// 已提交 (2) - 可以审核、删除
			else if (billindex === 2) {
				$opration.find('.edit').css('display', 'none')
				$opration.find('.submit').css('display', 'none')
				$opration.find('.antiaudit').css('display', 'none')
			}
			// 已审核 (3) - 可以反审核
			else if (billindex === 3) {
				$opration.find('.edit').css('display', 'none')
				$opration.find('.submit').css('display', 'none')
				$opration.find('.audit').css('display', 'none')
				$opration.find('.delete').css('display', 'none')
			}
			// 已删除 (99) - 只能查看
			else if (billindex === 99) {
				$opration.find('.edit').css('display', 'none')
				$opration.find('.submit').css('display', 'none')
				$opration.find('.audit').css('display', 'none')
				$opration.find('.antiaudit').css('display', 'none')
				$opration.find('.delete').css('display', 'none')
			}
		})

		// 点击功能可视区之外的区域
		$(document).bind("click", function(e) {
			var target = $(e.target);
			if (target.closest(".saleElp").length == 0) { //点击可视区域.saleElp之外的地方触发
				$(".saleElp").siblings('.detail').css('display', 'none')
			}
		})

		// 操作
		$(document).on('click', '.saledetail li:not(.operation)', function(e) {
			e.stopPropagation()
			index = $(this).parents('.looksale').index()
			let operat = $(this).index()
			operatsales(resTotal[index].id, operat)
			$(this).parents('.detail').css('display', 'none')
		});

		// 查看详情
		$(document).on('click', '.viewdetails', function(e) {
			e.stopPropagation()
			index = $(this).parents('.looksale').index()
			$(this).parents('.detail').css('display', 'none')
			// TODO: 跳转到详情页面，待创建
			$.toast('详情功能开发中...', 'forbidden');
			// location.href = `./pigprocurementplaninfo.html?v=${Utils.GetTime()}&id=${resTotal[index].id}`;
		})
		// 编辑
		$(document).on('click', '.edit', function(e) {
			e.stopPropagation()
			let id = $(this).data('id')
			$(this).parents('.detail').css('display', 'none')
			// TODO: 跳转到编辑页面，待创建
			$.toast('编辑功能开发中...', 'forbidden');
			// location.href = `./addpigprocurementplan.html?v=${Utils.GetTime()}&id=${id}`;
		});
	}

	// 提示
	const operatsales = (id, operat) => {
		$.modal({
			autoClose: false,
			title: `${operatarr[operat]}提示`,
			text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div  style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${operatarr[operat]}<span style="color:red">[${resTotal[index].billNo || ''}]</span > 单据？该操作无法撤销！</div >
					</div > `,
			buttons: [{
					text: "取消",
					className: "default",
					onClick: function() {
						$.closeModal();
					}
				},
				{
					text: "确定",
					onClick: function() {
						_initPage()
						let idsInfo = {
							ids: [id]
						}
						switch (operatarr[operat]) {
							case '删除':
								// TODO: 调用删除接口
								$.toast('删除功能暂未实现', 'forbidden');
								$.closeModal()
								// PigProcurementPlanApi.deletePigPurchasePlan(id).then(res => {
								//     _initDataTable();
								//     $.toptip('删除成功。', 'success');
								//     $.closeModal()
								// })
								break;
							case '审核':
								// TODO: 调用审核接口
								$.toast('审核功能暂未实现', 'forbidden');
								$.closeModal()
								break;
							case '反审核':
								// TODO: 调用反审核接口
								$.toast('反审核功能暂未实现', 'forbidden');
								$.closeModal()
								break;
						}
					}
				}
			]
		});
	}

	// 请求列表数据
	const _initDataTable = async () => {
		// 查询生猪采购计划列表
		let _data = _vm.page;
		let queryParams = {
			sort: 'bizFormObj.createTime desc'  // 按创建时间降序排序
		};

		// 添加日期筛选参数
		if (_dateFilter.startDate) {
			queryParams.startDate = _dateFilter.startDate;
		}
		if (_dateFilter.endDate) {
			queryParams.endDate = _dateFilter.endDate;
		}

		PigProcurementPlanApi.getPigPurchasePlanList(Object.assign(queryParams, _data)).then(res => {
			_page = {
				pageSize: 10,
				pageIndex: _data.pageIndex + 1,
				totalPages: res.totalPages
			}
			_vm._data.page = Object.assign({}, _page);
			_res = res.items
			resTotal.push(..._res)
			_res.forEach(ele => {
				// 将 bizFormObj 下的字段提取到顶层
				if (ele.bizFormObj) {
					Object.assign(ele, ele.bizFormObj);
				}
				// 根据单据状态显示对应的HTML标签
				ele.billStatusCh = auditStateToHtml(ele.billStatus)
			});
			_vm.salesplanList = []
			_vm.salesplanList = [..._vm.salesplanList, ...resTotal];
			$('.looksale:last').css('margin-bottom', '10px')
			$('#salesplantel').empty().append(salesplanmainTemplate(_vm.salesplanList));
			$('.looksale').eq(0).find('.saledetail').each(function(index, domele) {
				operatarr = $(domele).text().trim().split(' ')
			})
			$('.looksale:last').css('margin-bottom', '120px')
		})
	}

	// 初始化日期选择器
	const _initDatePicker = () => {
		// 开始日期选择器
		$('#startDate').on('click', function() {
			let currentValue = $(this).val() || moment(new Date()).format('YYYY-MM-DD');
			weui.datePicker({
				defaultValue: currentValue.split('-'),
				className: 'mypick',
				onConfirm: function(result) {
					let value = result.map(item => item.value).join('-');
					$('#startDate').val(value);
					_dateFilter.startDate = value;
					// 选择日期后自动查询
					_initPage();
					_initDataTable();
				}
			});
		});

		// 结束日期选择器
		$('#endDate').on('click', function() {
			let currentValue = $(this).val() || moment(new Date()).format('YYYY-MM-DD');
			weui.datePicker({
				defaultValue: currentValue.split('-'),
				className: 'mypick',
				onConfirm: function(result) {
					let value = result.map(item => item.value).join('-');
					$('#endDate').val(value);
					_dateFilter.endDate = value;
					// 选择日期后自动查询
					_initPage();
					_initDataTable();
				}
			});
		});

		// 重置按钮
		$('#resetDate').on('click', function() {
			$('#startDate').val('');
			$('#endDate').val('');
			_dateFilter.startDate = '';
			_dateFilter.endDate = '';
			_initPage();
			_initDataTable();
		});
	}

	// 初始化分页
	const _initPage = () => {
		resTotal = []
		_page = {
			pageSize: 10,
			pageIndex: 0,
			// totalPages: -1,
		}
		_vm._data.page = Object.assign({}, _page);
	}

	// 下拉加载
	const _initSlide = () => {
		//分别设置滑动距离，开始位置，结束位置，和模拟数据的定时器
		let disY, startY, endY, timer, t, pullheight;
		const $scrollContainer = $('#pigprocurementplanId');

		// 触摸开始
		$scrollContainer.on('touchstart', function(e) {
			startY = e.originalEvent.changedTouches[0].pageY; //开始时的坐标
		});
		// 移动中
		$scrollContainer.on('touchmove', function(e) {
			$(".saleElp").siblings('.detail').css('display', 'none')
			endY = e.originalEvent.changedTouches[0].pageY;
			disY = endY - startY; //移动后的坐标减去开始坐标，滑动距离。
			if (isTop() && disY > 0) {
				e.preventDefault();
			}
			if (disY < 60) {
				$('#pull-down').css({
					height: disY + 'px' //父盒子的高度随着滑动距离变化，有最大值。
				});
			} else {
				$('#pull-down').css({
					height: 60 + 'px' //父盒子的最大高度
				});
			}
			// 结束时
			$scrollContainer.on('touchend', function(e) {
				clearInterval(timer);
				endY = e.originalEvent.changedTouches[0].pageY;
				disY = endY - startY;
				if (isTop() && disY > 0) {
					timer = setInterval(function() {
						$('#pull-down').css({
							height: 0 + 'px', //松手后的返回。
						});
						clearInterval(timer);
						_initPage()
						_initDataTable(); //加载数据
					}, 300)
				} else {
					$('#pull-down').css({
						height: 0 + 'px', //松手后的返回。
					});
				}
				$scrollContainer.off('touchend')
			})
		});
	}
	const isTop = () => {
		var $scrollContainer = $('#pigprocurementplanId');
		var t = $scrollContainer.scrollTop();
		return t === 0 ? true : false;
	}

	//TODO : 上拉加载
	const pullLoad = () => {
		// 监听滚动容器
		$("#pigprocurementplanId").infinite().on("infinite", function() {
			let _data = _vm._data.page;
			if (_data.pageIndex == _data.totalPages) return;
			let self = this;
			if (self.loading) return;
			self.loading = true;
			setTimeout(function() {
				_initDataTable();
				self.loading = false;
			}, 500); //模拟延迟
		});
	}

	// 控制返回按钮，返回的页面
	const _ctlReturn = () => {
		if (window.history && window.history.pushState) {
			history.pushState(null, null, document.URL);
			window.addEventListener('popstate', function() {
				history.pushState(null, null, document.URL);
				//跳转列表
				this.window.location = `../../main.html`;
			});
		}
	}

	//返回首页
	const _returnMain = () => {
		$('#returnMain').on('click', function() {
			location.href = '../../main.html'
		});
	}

	// 添加水印信息
	const _watermarkBgImg = () => {
		let _userInfo = JSON.parse(Utils.GetSessionStorage("SNAccountEply")) || {};
		watermark.set(_userInfo.name + _userInfo.numCode); // 水印
	}
})(window, document, jQuery)